package com.data.modules.smzh.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.data.common.api.vo.Result;
import com.data.common.aspect.annotation.AutoLog;
import com.data.common.aspect.annotation.OnlineAuth;
import com.data.common.constant.CommonConstant;
import com.data.common.constant.MsgConstants;
import com.data.common.constant.WebsocketConst;
import com.data.common.constant.enums.DySmsEnum;
import com.data.common.constant.enums.EventEnum;
import com.data.common.constant.enums.ProductEnum;
import com.data.common.system.query.QueryGenerator;
import com.data.common.system.vo.DictModel;
import com.data.common.util.*;
import com.data.modules.base.service.BaseCommonService;
import com.data.modules.bd.entity.SmBdVideo;
import com.data.modules.bd.service.ISmBdVideoService;
import com.data.modules.demo.test.entity.JeecgOrderMain;
import com.data.modules.gd.entity.SmUpgradeVersion;
import com.data.modules.gd.service.IGdEventLogService;
import com.data.modules.gd.service.ISmUpgradeVersionService;
import com.data.modules.gd.vo.EventLogVo;
import com.data.modules.hotel.entity.SmzhHotelPhoto;
import com.data.modules.hotel.service.ISmzhHotelPhotoService;
import com.data.modules.jd.entity.JdOutCard;
import com.data.modules.jd.service.IJdOutCardService;
import com.data.modules.jd.vo.OutCarReqVo;
import com.data.modules.jhl.entity.SmJhlFall;
import com.data.modules.jhl.service.ISmJhlFallService;
import com.data.modules.jhl.service.ISmJhlSleepService;
import com.data.modules.message.entity.SysMessage;
import com.data.modules.message.websocket.WebSocket;
import com.data.modules.sm.entity.*;
import com.data.modules.sm.service.ISmProjectService;
import com.data.modules.sm.service.ISmRepairStatsService;
import com.data.modules.sm.service.ISysConfigService;
import com.data.modules.smapp.entity.SmAppAd;
import com.data.modules.smapp.entity.SmAppNews;
import com.data.modules.smapp.service.ISmAppAdService;
import com.data.modules.smapp.service.ISmAppNewsService;
import com.data.modules.smapp.vo.AdReqVo;
import com.data.modules.smzh.entity.*;
import com.data.modules.smzh.mapper.SmUserMapper;
import com.data.modules.smzh.service.*;
import com.data.modules.smzh.vo.*;
import com.data.modules.system.entity.User;
import com.data.modules.system.service.ISysDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.jeecgframework.poi.excel.entity.enmus.CellValueType.Date;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author boot
 */

@RestController
@RequestMapping("/face-app/api")
@Api(tags="app用户登录")
@Slf4j
@SuppressWarnings("ALL")
public class RegisterController<stringWarnType> {


	@Autowired
	private ISmCardLogService smCardLogService;
	@Autowired
	private RedisUtil redisUtil;
    @Resource
    private BaseCommonService baseCommonService;
	@Autowired
	private ISysConfigService sysConfigService;
	@Autowired
	private IRegisterService registerService;
	@Autowired
	private IRegisterappuserService registerAppUser;
	@Autowired
	private IFacedeviceService deviceService;
	@Autowired
	private IApplogService applogService;
	@Autowired
	private ISmUserService smUserService;
	@Autowired
	private ISmComAnnouncementService annMentService;
	@Autowired
	private ISmDeviceLogsService smDeviceLogsService;
	@Resource
	private WebSocket webSocket;
	@Autowired
	private ISmzhLimitNumService iSmzhLimitNumService;
	@Autowired
	private IBuildinguserService buildinguserService;
	@Autowired
	private IBuildingService buildingService;
	@Autowired
	private ISmzhCtiyCodeService smzhCtiyCodeService;
	@Autowired
	private ISmDeviceVersionService smDeviceVersionService;
	@Autowired
	private ISmThirdRegistService thirdRegistService;
	@Autowired
	private ISmRtspInfoService smRtspInfoService;
	@Autowired
	private ISmVideoSourceService smVideoSourceService;
	@Autowired
	private ISmSleepInfoService smSleepInfoService;
	@Autowired
	private ISmJhlFallService fallService;
	@Autowired
	private ISysDictService sysDictService;
	@Autowired
	private ISmAppNewsService smAppNewsService;
	@Autowired
	private ISmAppAdService smAppAdService;
	@Autowired
	private ISmzhScreenMsgService msgService;
	@Autowired
	private IOftenContactService oftenContactService;
	@Autowired
	private ISmProjectService smProjectService;
	@Value("${ys.url:}")
	private String ysUrl;
	@Value("${ys.appKey:}")
	private String ysAppKey;
	@Value("${ys.appSecret:}")
	private String ysAppSecret;
	@Autowired
	private ISmzhHotelPhotoService smzhHotelPhotoService;
	@Autowired
	private IGdEventLogService eventLogService;
	@Autowired
	private IJdOutCardService jdOutCardService;

	@Autowired
	private ISmBdVideoService videoService;


	@ApiOperation("用户修改")
	@PostMapping(value = "/v1.0/updateUser")
	public Result<?> updateUser(@RequestBody ReqUserVo user,HttpServletRequest req) {

		Result result = new Result();
		Integer code = 0;
		String appId = JwtIOTAuthUtil.getTokenByRequest(req);

		Map map = new HashMap();
		if (ObjectUtil.isEmpty(appId)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {
			code = smUserService.updateUserInfo(user,appId);
			result.setCode(code);
			result.setSuccess(true);
		}

		return  result;

	}

	@ApiOperation("松鼠app注销功能")
	@PostMapping(value = "/v1/cancelUser")
	public Result<String> cancelUser(@RequestBody User user)  {
		Result<String> result = new Result<String>();
		String mobile = user.getMobile();
		Register register = registerService.lambdaQuery().eq(Register::getMobile,mobile).one();
		if(ObjectUtil.isNotEmpty(register)){
			registerService.removeById(register.getId());

			LambdaQueryWrapper<Registerappuser> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(Registerappuser::getRegisterId,register.getId());
			registerAppUser.remove(wrapper);
		}
		return Result.OK();

	}
	/**
	 * 短信登录接口
	 *
	 * @param User
	 * @return
	 */
	@AutoLog(value = "松鼠app发送短信验证码")
	@ApiOperation("松鼠app发送短信验证码")
	@PostMapping(value = "/v1/getCode")
	public Result<String> getCode(@RequestBody User user) {
		Result<String> result = new Result<String>();
		String mobile = user.getMobile();
		LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(SysConfig::getCode,"sm_phone_switch");
		SysConfig sysConfig = sysConfigService.list(wrapper).get(0);

		log.info(mobile);
		if(ConvertUtils.isEmpty(mobile)){
			result.setMessage("手机号不允许为空！");
			result.setSuccess(false);
			return result;
		}

		Pattern p = Pattern.compile("^(192[0-9])\\d{7}$");
		Matcher m = p.matcher(mobile);

		if(ObjectUtil.equal("Y",sysConfig.getValue())){
			if(!m.matches()){
				result.setMessage("请输入合法的192号段的手机号！");
				result.setSuccess(false);
				return result;
			}
		}

		Object object = redisUtil.get(mobile);
		if (object != null) {
			result.setMessage("验证码已经发送");
			result.setCode(10004);
			result.setSuccess(false);
			return result;
		}

		//随机数
		String captcha = RandomUtil.randomNumbers(6);
		JSONObject obj = new JSONObject();
		obj.put("code", captcha);
		try {
			boolean b = false;

			b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.LOGIN_TEMPLATE_CODE);
			if (b == false) {
				result.setMessage("短信验证码发送失败,请稍后重试");
				result.setCode(10005);
				result.setSuccess(false);
				return result;
			}else{
				//验证码10分钟内有效
				redisUtil.set(mobile, captcha, 600);
				result.setSuccess(true);
			}

		} catch (ClientException e) {
			e.printStackTrace();
			result.error500("短信接口未配置，请联系管理员！");
			return result;
		}
		return result;
	}

	/**
	 * 注册用户
	 * @param user
	 * @return
	 */
	@ApiOperation("松鼠app注册")
	@PostMapping(value = "/v1/register")
	public Result<String> register(@RequestBody User user)  {
		Result<String> result = new Result<String>();
		String mobile = user.getMobile();
		String passWord = user.getPassword();

		Object code = redisUtil.get(user.getMobile());
		if(ObjectUtil.isEmpty(code)){
			result.setMessage("手机号不正确");
			result.setCode(10002);
			result.setSuccess(false);
			return result;
		}
		if (!user.getCode().equals(code)) {
			result.setMessage("验证码已过期");
			result.setCode(10002);
			result.setSuccess(false);
			return result;
		}

		//密码进行 aes解密  在进行dbaes 加密 储存到表
		return registerService.saveRegisterInfo(mobile,passWord);

	}
	@ApiOperation("松鼠app登录接口")
	@PostMapping(value = "/v1/login")
	public Result<Object> login(@RequestBody User user)  {
		Result<String> result = new Result<String>();
		String mobile = user.getMobile();
		String passWord = user.getPassword();

		//密码进行 aes解密  在进行dbaes 加密 储存到表
		return registerService.getRegisterInfo(mobile,passWord);

	}


	/**
	 * 首页用户重置密码
	 */
    //@RequiresRoles({"admin"})
	@ApiOperation("松鼠app重置密码")
    @PostMapping(value = "/v1/resetpassword")
	public Result<?> resetpassword(@RequestBody User user)  {

		Result<String> result = new Result<String>();
		Object code = redisUtil.get(user.getMobile());
		if(ObjectUtil.isEmpty(code)){
			result.setMessage("验证码已过期");
			result.setCode(10002);
			result.setSuccess(false);
			return result;
		}else{
			if(!ObjectUtil.equals(code,user.getCode())){
				result.setMessage("验证码已过期");
				result.setCode(10002);
				result.setSuccess(false);
				return result;

			}
		}

		return registerService.resetPassword(user.getMobile(),user.getNewPassword());
	}


	/*@AutoLog(value = "松鼠app查询设备")
	@ApiOperation(value="松鼠app查询设备", notes="查询设备")
	@GetMapping(value = "/v1/getAllDevice")
	public Result<?> getAllDevice(@RequestParam(name="id",required=false) String id,HttpServletRequest req) {

		Result<List> result = new Result<List>();
	*//*
		String userid = JwtIOTAuthUtil.getTokenByRequest(req);*//*
		String userid = id;

		if(ObjectUtil.isEmpty(userid)){
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		}else{
			//获取 resgitApp 信息
			Registerappuser registerappuser = registerAppUser.lambdaQuery()
					.eq(Registerappuser::getRegisterId,userid).one();
			if(ObjectUtil.isEmpty(registerappuser)){

				result.setMessage("failed");
				result.setCode(10001);
				result.setSuccess(false);
				return result;
			}else{
				//通过userId 查询设备信息
				List<Map> list = deviceService.getDeviceByUserId(registerappuser.getUserId());

				result.setResult(list);
				result.setData(list);
			}
		}

		return result;
	}
*/


	@ApiOperation(value="查询开门密码", notes="查询开门密码")
	@GetMapping(value = "/v1/getOpenDoorPassword")
	public Result<?> getOpenDoorPassword(@RequestParam(name="id",required=false) String id,HttpServletRequest req) {

		Result<Map> result = new Result<Map>();
		//String userid = JwtIOTAuthUtil.getTokenByRequest(req);
		String userid = id;
		if(ObjectUtil.isEmpty(userid)){
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		}else{

			//通过userId 查询密码
			String password= deviceService.getDoorPassword(userid);
			Map<String,Object> map = new HashMap<>();
			map.put("openDoorPassword",password);
			result.setResult(map);
			result.setData(map);
		}
		return result;
	}

	/**
	 * 首页用户重置密码
	 */
	//@RequiresRoles({"admin"})

	@ApiOperation("松鼠app修改开门密码")
	@PostMapping(value = "/v1/modifyOpenDoorPassword")
	public Result<?> modifyOpenDoorPassword(@RequestBody User user,HttpServletRequest req) {

		Result<Map> result = new Result<Map>();
		//String userid = JwtIOTAuthUtil.getTokenByRequest(req);
		String userid = user.getCode();
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {

			String serNo =Arrays.stream(user.getSerialNo()).collect(Collectors.joining());

			//通过userId 查询密码
			int i = deviceService.modifyOpenDoorPassword(userid, user.getNewOpenDoorPassword(), serNo);
			if (i == 0) {
				result.setMessage("failed");
				result.setCode(10001);
				result.setSuccess(false);
				return result;
			} else {
				result.setMessage("succeeded");
				result.setSuccess(true);
			}
		}
		return result;

	}

	@ApiOperation(value="查询已经登记的人脸", notes="查询已经登记的人脸")
	@GetMapping(value = "/v1/getPersonFace")
	public Result<?> getPersonFace(@RequestParam(name="id",required=false) String id,HttpServletRequest req) {

		/*Configuration config = new Configuration();
		config.setServiceHost("127.0.0.1");
		config.setServicePort(11300);
		config.setConnectTimeout(2000);
		config.setReadTimeout(3000);
		BeanstalkClientFactory factory = new BeanstalkClientFactory(config);

		BeanstalkClient beanstalkClient =  factory.createBeanstalkClient();
		//beanstalkClient.
		JobProducer producer = factory.createJobProducer("faceSync");
		//JobConsumer consumer = factory.createJobConsumer("faceSync");
		List<String> liststr = new ArrayList<>();
		liststr.add(id);

		Map map = new HashMap();
		map.put("serialNo",liststr);
		String msg = JSON.toJSONString(map);
		// String msg = "发送消息";
		// 返回job id
		long p = producer.putJob(2, 0, 5, msg.getBytes());
		log.error("====验证mq=====:"+p);
		producer.close();*/

		Result<List> result = new Result<List>();
		//String userid = JwtIOTAuthUtil.getTokenByRequest(req);
		String userid = id;
		if(ObjectUtil.isEmpty(userid)){
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		}else{
			//通过userId 查询获取人脸
			List<Map>list= deviceService.getPersonFace(userid);
			result.setResult(list);
			result.setData(list);
		}
		return result;
	}

	@ApiOperation("松鼠app删除人脸")
	@PostMapping(value = "/v1/delPersonFace")
	public Result<?> delPersonFace(@RequestBody User user,HttpServletRequest req) {

		Result<Map> result = new Result<Map>();
		//String userid = JwtIOTAuthUtil.getTokenByRequest(req);
		String userid = user.getCode();
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {

			String serialNo =Arrays.stream(user.getSerialNo()).collect(Collectors.joining());

			// 通过id  和序列号删除人脸照片
			int i = deviceService.delAppFace(user.getId(),serialNo);
			if (i == 0) {
				result.setMessage("failed");
				result.setCode(10001);
				result.setSuccess(false);
				return result;
			} else {
				result.setMessage("succeeded");
				result.setSuccess(true);
			}
		}
		return result;

	}
	@ApiOperation("松鼠app新增人脸")
	@PostMapping(value = "/v1/addPersonFace")
	public Result<?> addPersonFace(@RequestBody User user,HttpServletRequest req) {

		Result<Map> result = new Result<Map>();
		//String userid = JwtIOTAuthUtil.getTokenByRequest(req);
		String userid = user.getCode();
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {

			String serialNo =Arrays.stream(user.getSerialNo()).collect(Collectors.joining());

			// 通过id
			int i = deviceService.addAppFace(user);
			if (i == 0) {
				result.setMessage("failed");
				result.setCode(10001);
				result.setSuccess(false);
				return result;
			} else {
				result.setMessage("succeeded");
				result.setSuccess(true);
			}
		}
		return result;

	}


	@ApiOperation(value="松鼠app查询绑定的门口机设备", notes="松鼠app查询绑定的门口机设备")
	@GetMapping(value = "/v2/getAllDevices")
	public Result<?> getAllDevices(@RequestParam(name="id",required=false) String id,HttpServletRequest req) {

		Result<List> result = new Result<List>();
		String userid = id;

		if(ObjectUtil.isEmpty(userid)){
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		}else{
			//获取 resgitApp 信息
			Registerappuser registerappuser = registerAppUser.lambdaQuery()
					.eq(Registerappuser::getRegisterId,userid).one();
			if(ObjectUtil.isEmpty(registerappuser)){

				//result.setMessage("failed");
				result.setCode(0);
				//result.setSuccess(false);
				return result;
			}else{
				//通过userId 查询设备信息
				List<Map> list = deviceService.getDeviceByUserId(registerappuser.getUserId());
				//进行过滤
				List<Map> newlist = list.stream().filter(x->
					x.get("deviceType").equals(ProductEnum.SMW_721A10.getCode())
				).collect(Collectors.toList());

				result.setResult(newlist);
				result.setData(newlist);
			}
		}

		return result;
	}

	@ApiOperation("松鼠app访客邀请")
	@PostMapping(value = "/v2/inviteVisitors")
	public Result<?> inviteVisitors(@RequestBody VisitorInfo user, HttpServletRequest req) {

		Result<Map> result = new Result<Map>();
		String encryption = "";
		//String userid = JwtIOTAuthUtil.getTokenByRequest(req);
		String userid = user.getUserId();
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {

			String mobile = deviceService.queryMobile(user.getUserId());

			List<SmDeviceVo> devicelist = deviceService.queryDeviceList(mobile);
			//门禁机
			List<String> doorList = devicelist.stream().filter(x->x.getModel().equals(ProductEnum.SMW_721AC.getCode())).map(SmDeviceVo::getSerialNo).collect(Collectors.toList());
			//围墙机
			List<String> sns = user.getSerialNos();
			sns.addAll(devicelist.stream().filter(x->x.getModel().equals(ProductEnum.SMW_721A10W.getCode())).map(SmDeviceVo::getSerialNo).collect(Collectors.toList()));

			user.setSerialNos(sns.stream().distinct().collect(Collectors.toList()));

			int i = deviceService.addInviteVisitors(user);
			if (i == 0) {
				result.setMessage("failed");
				result.setCode(10001);
				result.setSuccess(false);
				return result;
			} else {

				try {
					encryption= deviceService.sendQrCode(user,mobile,doorList);

				} catch (Exception e) {
					log.error("AES加密异常",e.getMessage(),e);
					result.setMessage("failed");
					result.setCode(10001);
					result.setSuccess(false);
					return result;
				}

				result.setMessage(encryption);
				result.setSuccess(true);
			}
		}
		return result;

	}

	@ApiOperation("松鼠app修改开门密码")
	@PostMapping(value = "/v2/modifyOpenDoorPassword")
	public Result<?> modifyOpenDoorPassword(@RequestBody VisitorInfo user, HttpServletRequest req) {

		Result<Map> result = new Result<Map>();
		//String userid = JwtIOTAuthUtil.getTokenByRequest(req);
		String userid = user.getUserId();
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {
			user.getSerialNos().stream().forEach(x->{
				deviceService.modifyOpenDoorPassword(userid, user.getNewOpenDoorPassword(), x);

				List list = new ArrayList();
				Map msgMap = new HashMap();
				msgMap.put("invitePassowrd",user.getNewOpenDoorPassword());
				msgMap.put("startTime","2023-01-01 00:00:00");
				msgMap.put("endTime","2099-12-31 00:00:00");
				list.add(msgMap);

				KamliClientUtil.doPostpushMsgUr(x,"inviteCode",list);
			});

			result.setMessage("succeeded");
			result.setSuccess(true);

		}
		return result;

	}

	@ApiOperation("松鼠app查询通行记录")
	@PostMapping(value = "/v1/getLogs")
	public Result<?> getLogs(@RequestBody VisitorInfo user, HttpServletRequest req) {

		Result<IPage> result = new Result<IPage>();
		//String userid = JwtIOTAuthUtil.getTokenByRequest(req);
		String userid = user.getUserId();
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {

			LambdaQueryWrapper<Applog> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(Applog::getRegisterId,user.getUserId());

			Page<Applog> page = new Page<Applog>(user.getPage(), user.getPageSize());
			IPage<Applog> pageList = applogService.page(page, wrapper);

			result.setData(pageList);
			result.setResult(pageList);
			result.setMessage("succeeded");
			result.setSuccess(true);
		}
		return result;

	}

	@ApiOperation("松鼠app开门")
	@PostMapping(value = "/v1/appOpenDoor")
	public Result<?> appOpenDoor(@RequestBody VisitorInfo user, HttpServletRequest req) {

		Result<IPage> result = new Result<IPage>();
		//String userid = JwtIOTAuthUtil.getTokenByRequest(req);
		String userid = user.getUserId();
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {

			//curl 调用设备开门
			if(!DeviceClientUtil.doPostOpenDoorJson(user.getSerialNo())){
				result.setMessage("开门失败");
				result.setCode(10008);
				result.setSuccess(false);
				return result;
			}
			result.setMessage("succeeded");
			result.setSuccess(true);
		}
		return result;

	}

	@ApiOperation(value="外部接口调用刷卡记录日志表-添加", notes="外部接口调用刷卡记录日志表-添加")
	@PostMapping(value = "/v1/addDeviceLog")
	public Result<?> addDeviceLog(@RequestBody SmDeviceLogs smDeviceLogs) {
		String userId = "1000000";
		userId = queryDeviceOwnId(smDeviceLogs);

		if(ObjectUtil.isEmpty(smDeviceLogs.getEventName())){

			String codeName = sysDictService.queryDictTextByKey("smzh_event_code", String.valueOf(smDeviceLogs.getEventCode()));
			smDeviceLogs.setEventName(codeName);
		}

		smDeviceLogsService.saveInfo(smDeviceLogs, userId);
		return Result.OK("添加成功！");
	}

	/**
	 * 通过日志上报查询 项目的创建者
	 * @param smDeviceLogs
	 * @return
	 */
	private String queryDeviceOwnId(SmDeviceLogs smDeviceLogs) {

		//通过设备编号查询到该项目appid
		String accountMobile ="";
		String appid = "";

		if(ObjectUtil.equals(1,smDeviceLogs.getDeviceType())){//门口机
			Facedevice facedevice = deviceService.lambdaQuery().eq(Facedevice::getSerialNo,smDeviceLogs.getDeviceId()).one();
			if(ObjectUtil.isNotEmpty(facedevice)){

				appid = String.valueOf(facedevice.getAppId());
			}

		}else{//智慧屏
			Building  building = buildingService.lambdaQuery().eq(Building::getUniqueNo,smDeviceLogs.getDeviceId()).one();
			if(ObjectUtil.isNotEmpty(building)){
				appid = String.valueOf(building.getAppId());
			}
		}

		accountMobile= deviceService.queryDevelAccountMobileByAppID(appid);
		smDeviceLogs.setCreateBy(accountMobile);

		return accountMobile;
	}

	@ApiOperation(value="门口机查询公告信息", notes="门口机查询公告信息-查询")
	@PostMapping(value = "/v1/queryAnncment")
	public Result<?> queryAnncment(@RequestBody SmCardLog smCardLog) {

		List<SmComAnnouncement> list = annMentService.lambdaQuery().eq(SmComAnnouncement::getSerialNo,smCardLog.getSerialNo()).list();
		return Result.OK(list);
	}

	@ApiOperation(value="今日限号-查询", notes="今日限号-查询")
	@PostMapping(value = "/v1/queryLimitNum")
	public Result<?> queryLimitNum(@RequestBody SmzhLimitNum smzhLimitNum) {
		String msg = "";
		if(ObjectUtil.isNotEmpty(smzhLimitNum.getCityName())){
			 msg = iSmzhLimitNumService.queryDayLimitNum(smzhLimitNum.getCityName());
		}else{
			msg = iSmzhLimitNumService.queryDayLimitByCityCode(smzhLimitNum.getCityCode());

			msg = msg.replaceAll("和",",").replaceAll("不限号","");

		}

		Map map = new HashMap();
		map.put("limitNum",msg);
		return Result.OK(map);
	}

	@ApiOperation(value="紧急报警消息已处理", notes="紧急报警消息已处理")
	@PostMapping(value = "/v1/handleAlarm")
	public Result<?> handleAlarm(@RequestBody SmDeviceLogs smDeviceLogs) {

		LambdaUpdateWrapper<SmDeviceLogs> wrapper = new LambdaUpdateWrapper<>();
		wrapper.eq(SmDeviceLogs::getId,smDeviceLogs.getId());
		wrapper.set(SmDeviceLogs::getStatus,1);
		wrapper.set(SmDeviceLogs::getUpdateTime,new Date());

		smDeviceLogsService.update(wrapper);
		//发送物业大屏消息
		JSONObject obj = new JSONObject();
		obj.put(WebsocketConst.MSG_TYPE,"-1");//紧急报警已处理 "-1"
		webSocket.sendMessage(obj.toJSONString());

		return Result.OK();
	}

	@ApiOperation(value="管理机、智慧屏、门口机 获取绑定的门口机信息", notes="管理机、智慧屏、门口机 获取绑定的门口机信息")
	@PostMapping(value = "/v1/queryManageBaseInfo")
	public Result<?> queryManageBaseInfo(@RequestBody SmDeviceVo smDeviceVo) {

		List<SmDeviceVo> list = deviceService.seachManageBaseInfo(smDeviceVo)
				.stream().filter(x->!x.getSerialNo().equals(smDeviceVo.getSerialNo()))
				.filter(x->x.getModel().equals(ProductEnum.SMW_721A10.getCode()))
				.collect(Collectors.toList());

		return Result.OK(list);
	}


	/**
	 * 文件上传统一方法
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value="录音上报", notes="录音上报")
	@PostMapping(value = "/v1/recordUpload")
	public Result<?> recordUpload(HttpServletRequest request, HttpServletResponse response) {

		String savePath = "";
		String toUser = request.getParameter("toUser");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象

		savePath = CommonUtils.upload(file, toUser, "fastdfs");

		List list = new ArrayList();
		Map map = new HashMap();
		map.put("recordAddress",savePath);
		map.put("time",DateUtils.now());
		list.add(map);

		//发送消息
		boolean b = KamliClientUtil.doPostpushMsgUr(toUser,"recordMessage",list);
		if(b){
			return Result.ok();
		}else{
			return Result.error("留言失败");
		}

	}

	/**
	 *  获取天气预报
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value="获取当天天气预报", notes="获取当天天气预报")
	@PostMapping(value = "/v1/queryWeatherInfo")
	public Result<?> queryWeatherInfo(@RequestBody WeatherVo weatherVo) {
		Result results = new Result();
		if(MD5Util.check() == Boolean.TRUE ) {
			results.error500("系统错误,请联系管理员");
			return results;
		}

		String city = weatherVo.getCity();
		if(ObjectUtil.isEmpty(city)){
			SmzhCtiyCode smzhCtiyCode = smzhCtiyCodeService.lambdaQuery().eq(SmzhCtiyCode::getCitycode,weatherVo.getCityCode()).one();

			if(ObjectUtil.isEmpty(smzhCtiyCode)){
				return Result.error("请核实城市区号");
			}
			city = smzhCtiyCode.getName();

		}
		Map<String,Object>map = new HashMap<>();
		String result = "";

		String url = "https://api.seniverse.com/v3/weather/daily.json?key=ShVxngfu3Ta8D44Zj&language=zh-Hans&unit=c&start=0&days=1&location="+city;
		//查询城市级别天气预报
		if(ObjectUtil.isNotEmpty(city)){
			result = HttpClientUtil.doGet(url);
		}
		if(ObjectUtil.isNotEmpty(result)){

			WeatherResult weatherResult = JSON.parseObject(result, WeatherResult.class);
			List<Results> list = weatherResult.getResults();
			Results vo = list.get(0);
			WaDaily waDaily = vo.getDaily().get(0);
			map.put("status",waDaily.getText_day());
			map.put("temperature",waDaily.getLow()+"~"+waDaily.getHigh()+"°C");
		}
		return Result.ok(map);

	}

	@ApiOperation(value="设备版本通知接口", notes="设备版本通知接口")
	@PostMapping(value = "/v1/noticeVersion")
	public Result<?> noticeVersion(@RequestBody SmDeviceVersion deviceVersion) {

		return smDeviceVersionService.updateResultInfo(deviceVersion);

	}

	@ApiOperation(value="设备版本通知接口", notes="设备版本通知接口(新闻屏)")
	@PostMapping(value = "/v2/noticeVersion")
	public Result<?> noticeVersion2(@RequestBody SmDeviceVersion deviceVersion) {
		Result result = new Result();
		if(MD5Util.check() == Boolean.TRUE ) {
			result.error500("系统错误,请联系管理员");
			return result;
		}

		return smDeviceVersionService.updateV2ResultInfo(deviceVersion);
	}

	@ApiOperation(value="新闻屏上传事件接口", notes="新闻屏上传事件接口")
	@PostMapping(value = "/v1/addEventLog")
	public Result<?> addEventLog(@RequestBody EventLogVo eventLogVo) {
		Result result = new Result();
		if(MD5Util.check() == Boolean.TRUE ) {
			result.error500("系统错误,请联系管理员");
			return result;
		}

		eventLogService.addEventLog(eventLogVo);
		return Result.OK();
	}

	@ApiOperation(value="酒店获取照片接口", notes="酒店获取照片接口")
	@PostMapping(value = "/v1/queryPhoneByType")
	public Result<?> queryPhoneByType(@RequestBody SmzhHotelPhoto hotelPhoto) {

		List<SmzhHotelPhoto> list = smzhHotelPhotoService.lambdaQuery().eq(SmzhHotelPhoto::getType,hotelPhoto.getType()).list();

		return Result.OK(list);
	}

	@ApiOperation("松鼠app开门v2")
	@PostMapping(value = "/v2/appOpenDoor")
	public Result<?> appVopenDoor(@RequestBody VisitorInfo user, HttpServletRequest req) {

		Result<IPage> result = new Result<IPage>();
		String userid = user.getUserId();
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {

			String sipNo = user.getSerialNo();
			String cmdCode = "onekeyunlock";
			List list = new ArrayList();
			Map<String,Object> map = new HashMap<>();
			map.put("type",user.getType());
			map.put("sipNo",sipNo);
			list.add(map);

			//curl 调用设备开门
			if(!KamliClientUtil.doPostOpenDoor(sipNo,cmdCode,list)){
				result.setMessage("开门失败");
				result.setCode(10008);
				result.setSuccess(false);
				return result;
			}
			result.setMessage("succeeded");
			result.setSuccess(true);
		}
		return result;

	}

	@ApiOperation(value="查看龙侨华账号信息", notes="查看龙侨华账号信息")
	@PostMapping(value = "/v1/getThirdAccount")
	public Result<?> getThirdAccount(@RequestBody VisitorInfo visitorInfo) {

		Map<String,Object>map = new HashMap<>();
		String buildNo = visitorInfo.getUserId();

		//通过建筑编号 查询账号信息
		SmThirdRegist smThirdRegist = thirdRegistService.lambdaQuery().eq(SmThirdRegist::getUniqueNo,buildNo).eq(SmThirdRegist::getStatus,2).one();

		if(ObjectUtil.isNotEmpty(smThirdRegist)){
			map.put("username",smThirdRegist.getUserName());
			map.put("password",smThirdRegist.getPassWord());
		}

		return Result.ok(map);
	}

	/**
	 * 获取用户相关信息
	 * @param weatherVo
	 * @return
	 */
	@ApiOperation(value="获取住户相关信息", notes="获取住户相关信息")
	@PostMapping(value = "/v1/queryUserInfo")
	public Result<?> queryUserInfo(@RequestBody String[] userIds) {

		if(ObjectUtil.isEmpty(userIds)){
			return Result.error("请求参数必填");
		}
		List<String> Arrary = Arrays.asList(userIds);
		//批量查询用户
		List list = smUserService.queryUserInfoByIds(Arrary);

		return Result.ok(list);

	}

	@ApiOperation(value="时迈摄像头映射地址-分页列表查询", notes="时迈摄像头映射地址-分页列表查询")
	@PostMapping(value = "/queryRtspInfoByRoomNo")
	public Result<?> queryRtspInfoByRoomNo(@RequestBody  SmRtspInfo smRtspInfo) {

		List<SmRtspInfo> pageList = smRtspInfoService.lambdaQuery().eq(SmRtspInfo::getAppId,smRtspInfo.getAppId()).list();
		return Result.OK(pageList);
	}

	/*@AutoLog(value = "视频资源")
	@ApiOperation(value="视频资源查询", notes="视频资源查询")
	@PostMapping(value = "/queryVideoInfo")
	public Result<?> queryVideoInfo(@RequestBody SmVideoSource smVideoSource) {

		List<SmVideoSource>list = smVideoSourceService.lambdaQuery().eq(SmVideoSource::getAppId,smVideoSource.getAppId()).list();
		return Result.OK(list);
	}*/

	@ApiOperation(value="视频资源查询", notes="视频资源查询")
	@PostMapping(value = "/queryVideoInfo")
	public Result<?> queryVideoInfo(@RequestBody SmVideoSource smVideoSource) {

		List<SmVideoSource>list = smVideoSourceService.lambdaQuery().list();
		return Result.OK(list);
	}

	/*@AutoLog(value = "睡眠监测")
	@ApiOperation(value="睡眠监测查询", notes="睡眠监测查询")
	@PostMapping(value = "/querySleepInfo")
	public Result<?> querySleepInfo(@RequestBody SmSleepInfo sleepInfo) {

		List<SmSleepInfo>list = smSleepInfoService.lambdaQuery().eq(SmSleepInfo::getRoomNo,sleepInfo.getRoomNo()).list();
		return Result.OK(list);
	}*/

	@ApiOperation(value="睡眠监测查询", notes="睡眠监测查询")
	@PostMapping(value = "/querySleepInfo")
	public Result<?> querySleepInfo(@RequestBody SmSleepInfo sleepInfo) {

		List<SmSleepInfo>list = smSleepInfoService.lambdaQuery().list();
		return Result.OK(list);
	}

	@ApiOperation(value="事件检测查询", notes="事件检测查询")
	@PostMapping(value = "/queryEventInfo")
	public Result<?> queryEventInfo(@RequestBody SmJhlFall smJhlFall) {

		List<SmJhlFall>list = fallService.lambdaQuery().eq(SmJhlFall::getRoomNo,smJhlFall.getRoomNo()).list();
		return Result.OK(list);
	}



	@ApiOperation(value="门口机呼叫通知", notes="门口机呼叫通知")
	@PostMapping(value = "/v1/addCallNotice")
	public Result<?> addCallNotice(@RequestBody SmDeviceVo smDeviceVo) {

		log.info("addCallNotice请求参数{}",JSON.toJSON(smDeviceVo));
		//通过建筑编号查询app id
		String alert = DateUtils.now().concat(" ").concat("门口机呼叫") ;
		List<String> list = deviceService.queryAppRegistId(smDeviceVo.getUniqueNo());
		if(ObjectUtil.isNotEmpty(list)){

			try{
				list.stream().forEach(x->{
					String result = JiguangPushUtils.jgPush(alert,x,false);
					net.sf.json.JSONObject resData = net.sf.json.JSONObject.fromObject(result);
					if(resData.containsKey("error")){
						log.info("针对别名为" + x + "的信息推送失败！");
						net.sf.json.JSONObject error = net.sf.json.JSONObject.fromObject(resData.get("error"));
						log.info("错误信息为：" + error.get("message").toString());
					}
					log.info("针对别名为" + x + "的信息推送成功！");
				});


			}catch(Exception e){
				log.error("针对别名为" + list + "的信息推送失败！",e,e.getMessage());
			}
		}

		return Result.OK();
	}

	@ApiOperation(value="新版视频资源查询", notes="新版视频资源查询")
	@PostMapping(value = "/v1/queryNewVideoInfo")
	public Result<?> queryNewVideoInfo(@RequestBody VideoReqVo videoReqVo) {
		Result result = new Result();
		if(MD5Util.check() == Boolean.TRUE ) {
			result.error500("系统错误,请联系管理员");
			return result;
		}

		List<SmVideoSource>list = smVideoSourceService.lambdaQuery().eq(SmVideoSource::getType,videoReqVo.getType()).list();
		List<VideoReqVo> copyList = BeanUtil.copyToList(list,VideoReqVo.class);
		return Result.OK(copyList);
	}

	@ApiOperation(value="查询视频资源类型", notes="查询视频资源类型")
	@GetMapping(value = "/v1/queryVideoType")
	public Result<?> queryVideoType() {
		Result result = new Result();
		if(MD5Util.check() == Boolean.TRUE ) {
			result.error500("系统错误,请联系管理员");
			return result;
		}
		List<DictModel> list = sysDictService.queryDictItemsByCode("sm_video_type");

		return Result.OK(list);
	}


	@ApiOperation(value="app查询新闻热点", notes="app查询新闻热点")
	@PostMapping(value = "/v1/queryNews")
	public Result<?> queryNews(@RequestBody SmAppNews smAppNews) {

		log.info("请求参数{}",JSON.toJSON(smAppNews));
		List<SmAppNews>list = smAppNewsService.lambdaQuery().eq(SmAppNews::getType,smAppNews.getType()).list();

		return Result.ok(0,list);
	}
	@ApiOperation(value="app查询新闻热点v2", notes="app查询新闻热点v2")
	@PostMapping(value = "/v2/queryNews")
	public Result<?> queryNewsV2(@RequestBody SmAppNews smAppNews) {
		Result result = new Result();
		if(MD5Util.check() == Boolean.TRUE ) {
			result.error500("系统错误,请联系管理员");
			return result;
		}
		//List<SmAppNews>list = smAppNewsService.lambdaQuery().eq(SmAppNews::getType,smAppNews.getType()).eq(SmAppNews::getUrlType,2).list();

		List<SmAppNews>list = smAppNewsService.lambdaQuery().eq(SmAppNews::getType,smAppNews.getType()).list();
		return Result.ok(200,list);
	}

	@ApiOperation(value="app查询新闻热点v3", notes="app查询新闻热点v3")
	@PostMapping(value = "/v3/queryNews")
	public Result<?> queryNewsV3(@RequestBody SmAppNews smAppNews) {

		log.info("请求参数{}",JSON.toJSON(smAppNews));
		List<SmAppNews>list = smAppNewsService.lambdaQuery().eq(SmAppNews::getType,smAppNews.getType()).list();

		return Result.ok(200,list);
	}

	@ApiOperation(value="app查询广告位", notes="app查询广告位")
	@PostMapping(value = "/v1/queryAdvertisement")
	public Result<?> queryAdvertisement(@RequestBody AdReqVo appAd) {

		log.info("请求参数{}",JSON.toJSON(appAd));
		List<SmAppAd>list = smAppAdService.lambdaQuery().eq(SmAppAd::getType,appAd.getType()).list();

		List<AdReqVo> copyList =BeanUtil.copyToList(list,AdReqVo.class);

		return Result.ok(0,copyList);
	}
	@ApiOperation(value="app查询物业通知信息", notes="app查询物业通知信息")
	@PostMapping(value = "/v1/queryPropertyNotice")
	public Result<?> queryPropertyNotice(@RequestBody SmBuilding smBuilding ,HttpServletRequest req) {
		Result result = new Result();
		String userid = "11";//JwtIOTAuthUtil.getTokenByRequest(req);
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {
			log.info("请求参数{}",JSON.toJSON(smBuilding));
			//根据建筑编号查询所在小区 物业公告
			List<SmzhScreenMsg>list = msgService.queryNoticeByBuildNo(smBuilding.getUniqueNo());

			return Result.ok(0,list);
		}

	}

	@ApiOperation(value="app查询物业联系电话", notes="app查询物业联系电话")
	@PostMapping(value = "/v1/queryPropertyPhone")
	public Result<?> queryPropertyPhone(@RequestBody SmBuilding smBuilding ,HttpServletRequest req) {

		Result result = new Result();
		String userid = "11";//JwtIOTAuthUtil.getTokenByRequest(req);
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {
			log.info("请求参数{}",JSON.toJSON(smBuilding));
			//根据建筑编号查询所在小区物业联系方式
			List<OftenContact> list = oftenContactService.searchPhoneInfo(smBuilding.getUniqueNo());

			return Result.ok(0,list);
		}

	}

	@ApiOperation(value="app查询绑定的建筑编号通过手机号", notes="app查询绑定的建筑编号通过手机号")
	@PostMapping(value = "/v1/queryBuildInfoByMobile")
	public Result<?> queryBuildInfoByMobile(@RequestBody User user,HttpServletRequest req) {

		Result result = new Result();
		String userid = "11";//JwtIOTAuthUtil.getTokenByRequest(req);
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {

			log.info("请求参数{}",JSON.toJSON(user));
			SmUser smUser = smUserService.lambdaQuery().eq(SmUser::getPersonCode,user.getMobile()).one();
			if(ObjectUtil.isNotEmpty(smUser)){
				Buildinguser buildinguser = buildinguserService.lambdaQuery().eq(Buildinguser::getUserId,smUser.getId()).one();
				//查询绑定
				int i = registerAppUser.lambdaQuery().eq(Registerappuser::getUserId,smUser.getId()).count();
				if(ObjectUtil.isNotEmpty(buildinguser) && i < 1){

					Register register = registerService.lambdaQuery().eq(Register::getMobile,user.getMobile()).one();
					Registerappuser vo =  new Registerappuser();
					vo.setAppId(smUser.getAppId());
					vo.setUserId(smUser.getId());
					vo.setRegisterId(register.getId());
					registerAppUser.save(vo);
				}

				if(ObjectUtil.isNotEmpty(buildinguser)){
					Building building = buildingService.lambdaQuery().eq(Building::getUniqueNo,buildinguser.getUniqueNo()).one();
					SmProject smProject = smProjectService.lambdaQuery().eq(SmProject::getAppId,building.getAppId()).eq(SmProject::getProjectNo,building.getProjectNo()).one();
					building.setProjectName(smProject.getProjectName());
					return Result.ok(0,building);
				}
			}
			result.setCode(0);
			return result;
		}
	}

	@ApiOperation(value="查看数据统计", notes="查看数据统计")
	@PostMapping(value = "/v1/queryDataTotal")
	public Result<?> queryDataTotal(@RequestBody User user) {

		log.info("请求参数{}",JSON.toJSON(user));

		Result result = new Result();
		String userid = "11";//JwtIOTAuthUtil.getTokenByRequest(req);
		if (ObjectUtil.isEmpty(userid)) {
			result.setMessage("token失效");
			result.setCode(10008);
			result.setSuccess(false);
			return result;
		} else {

			Map map = smUserService.queryData(user.getName());
			result.setData(map);
			result.setCode(0);
			return  result;
		}
	}

	@ApiOperation(value="查看设备数据统计", notes="查看设备数据统计")
	@PostMapping(value = "/v1/queryDeviceDataTotal")
	public Result<?> queryDeviceDataTotal(@RequestBody User user) {

		log.info("请求参数{}",JSON.toJSON(user));

		Result result = new Result();

		List<Map> map = smUserService.queryDeviceData(user.getName());
		result.setData(map);
		result.setCode(0);
		return  result;
	}

	@ApiOperation(value="查看最近7天新增用户数据统计", notes="查看最近7天新增用户数据统计")
	@PostMapping(value = "/v1/queryAddUserTotal")
	public Result<?> queryAddUserTotal(@RequestBody User user) {

		log.info("请求参数{}",JSON.toJSON(user));
		Result result = new Result();

		List<Map> map = smUserService.queryAddUserTotal(user.getName());
		result.setData(map);
		result.setCode(0);
		return  result;
	}

	@ApiOperation(value="添加授权", notes="添加授权")
	@PostMapping(value = "/v1/addBindUserAndDevice")
	public Result<?> addBindUserAndDevice(@RequestBody SmUserInfoVO user) {

		Result result = new Result();
		if(MD5Util.check() == Boolean.TRUE ) {
			result.error500("系统错误,请联系管理员");
			return result;
		}

		Map map = smUserService.queryBindUserAndDevice(user);
		result.setData(map);
		result.setCode(0);

		return  result;
	}

	@ApiOperation(value="查授权信息", notes="查授权信息")
	@PostMapping(value = "/v1/queryBindUserAndDeviceInfo")
	public Result<?> queryPagequeryBindUserAndDeviceInfoList(@RequestBody SmUserInfoVO user ,
								   HttpServletRequest req) {

		List<Map> list = smUserService.authPageList(user);
		return Result.OK(list);
	}

	@ApiOperation(value="查看车辆进出数据", notes="查看车辆进出数据")
	@PostMapping(value = "/v1/queryCarInfo")
	public Result<?> queryJdCarInfo(@RequestBody OutCarReqVo jdOutCard){

		QueryWrapper<JdOutCard> queryWrapper = new QueryWrapper<>() ;
		queryWrapper.lambda().eq(JdOutCard::getCreateBy,jdOutCard.getCreateBy())
		.eq(ObjectUtil.isNotEmpty(jdOutCard.getCarNum()),JdOutCard::getCarNum,jdOutCard.getCarNum())
				.ge(ObjectUtil.isNotEmpty(jdOutCard.getBegin()),JdOutCard::getCreateTime,jdOutCard.getBegin())
				.le(ObjectUtil.isNotEmpty(jdOutCard.getEnd()),JdOutCard::getCreateTime,jdOutCard.getEnd())
				.ge(JdOutCard::getCreateTime, DateUtil.offsetDay(new Date(),-11))
		.orderByDesc(JdOutCard::getCreateTime);

		Page<JdOutCard> page = new Page<JdOutCard>(jdOutCard.getPi(), jdOutCard.getPs());
		IPage<JdOutCard> pageList = jdOutCardService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@ApiOperation(value="爱牵挂消息", notes="爱牵挂消息")
	@GetMapping(value = "/messageInfo")
	public Result<?> messageInfo(MessageReqVo messageReqVo) {

		log.info("爱牵挂消息请求参数{}",JSON.toJSON(messageReqVo));
		return Result.ok();
	}

	@ApiOperation(value="爱牵挂跌倒报警消息", notes="爱牵挂跌倒报警消息")
	@PostMapping(value = "/fallInfo")
	public Result<?> fallInfo(@RequestBody AFallReqVo aFallReqVo) {

		log.info("爱牵挂跌倒报警消息请求参数{}",JSON.toJSON(aFallReqVo));
		SmDeviceLogs smDeviceLogs = new SmDeviceLogs();
		smDeviceLogs.setDeviceId(aFallReqVo.getImei());
		smDeviceLogs.setEventName(aFallReqVo.getAddress());
		smDeviceLogs.setDeviceType(3);

		smDeviceLogsService.sendMessage(smDeviceLogs,"smVip009", EventEnum.TYPE_SERVE.getCode());
		return Result.ok();
	}


	@ApiOperation(value="爱牵挂SOS报警消息", notes="爱牵挂SOS报警消息")
	@PostMapping(value = "/sosInfo")
	public Result<?> sosInfo(@RequestBody ASosReqVo aSosReqVo) {

		log.info("爱牵挂SOS报警消息请求参数{}",JSON.toJSON(aSosReqVo));

		SmDeviceLogs smDeviceLogs = new SmDeviceLogs();
		smDeviceLogs.setDeviceId(aSosReqVo.getImei());
		smDeviceLogs.setEventName(aSosReqVo.getAddress());
		smDeviceLogs.setDeviceType(3);

		smDeviceLogsService.sendMessage(smDeviceLogs,"smVip009",EventEnum.TYPE_EMERG.getCode());
		return Result.ok();
	}

	@ApiOperation(value="爱牵挂位置信息", notes="爱牵挂位置信息")
	@PostMapping(value = "/positionInfo")
	public Result<?> positionInfo(@RequestBody APositionReqVo aPositionReqVo) {

		log.info("爱牵挂位置信息请求参数{}",JSON.toJSON(aPositionReqVo));
		return Result.ok();
	}


	@ApiOperation(value="爱牵挂心率", notes="爱牵挂心率")
	@PostMapping(value = "/heartRateInfo")
	public Result<?> heartRateInfo(@RequestBody AHeartReqVo aHeartReqVo) {

		log.info("爱牵挂心率信息请求参数{}",JSON.toJSON(aHeartReqVo));
		return Result.ok();
	}

	@ApiOperation(value="爱牵挂步数", notes="爱牵挂步数")
	@PostMapping(value = "/stepInfo")
	public Result<?> stepInfo(@RequestBody AStepReqVo aStepReqVo) {

		log.info("爱牵挂步数信息请求参数{}",JSON.toJSON(aStepReqVo));
		return Result.ok();
	}

	@ApiOperation(value="爱牵挂睡眠", notes="爱牵挂睡眠")
	@PostMapping(value = "/sleepInfo")
	public Result<?> sleepInfo(@RequestBody ASleepReqVo aSleepReqVo) {

		log.info("爱牵挂睡眠信息请求参数{}",JSON.toJSON(aSleepReqVo));
		return Result.ok();
	}

	@ApiOperation(value="爱牵挂血压", notes="爱牵挂血压")
	@PostMapping(value = "/bPressureInfo")
	public Result<?> bPressureInfo(@RequestBody APressureReqVo aPressureReqVo) {

		log.info("爱爱牵挂血压信息请求参数{}",JSON.toJSON(aPressureReqVo));
		return Result.ok();
	}


	@ApiOperation(value="爱牵挂血氧", notes="爱牵挂血氧")
	@PostMapping(value = "/bNutrientInfo")
	public Result<?> bNutrientInfo(@RequestBody ANutrientReqVo nutrientReqVo) {

		log.info("爱牵挂血氧信息请求参数{}",JSON.toJSON(nutrientReqVo));
		return Result.ok();
	}


	@ApiOperation(value="获取萤石token", notes="获取萤石token")
	@GetMapping(value = "/v1/getToken")
	public Result<?> getToken() {

		Result<String> result = new Result<String>();

		//String url = "https://open.ys7.com/api/lapp/token/get";
		Map<String,String> map = new HashMap<>();
		map.put("appKey",ysAppKey);
		map.put("appSecret",ysAppSecret);

		String str = HttpClientUtil.doPost(ysUrl,map);
		JSONObject jsonObject = JSONObject.parseObject(str);
		JSONObject token = JSONObject.parseObject(jsonObject.getString("data"));
		result.setResult(token.getString("accessToken"));
		return result;
	}

	/**
	 *   通过设备序列号查询设备是否停机
	 *
	 * @param smDeviceVersion
	 * @return
	 */
	@ApiOperation(value="查询设备是否停机", notes="查询设备是否停机")
	@PostMapping(value = "/v2/queryDeviceIsStop")
	public Result<?> queryDeviceIsStopV2(@RequestBody SmDeviceVersion version) {

		Boolean flag = Boolean.TRUE;
		Map<String,Object> map = new HashMap<>();
		List<SmDeviceVersion> list = smDeviceVersionService.lambdaQuery().eq(SmDeviceVersion::getSn,version.getSn())
				.eq(SmDeviceVersion::getStatus,0).list();
		if(ObjectUtil.isNotEmpty(list)){
			SmDeviceVersion deviceVersion =list.get(0);
			if(ObjectUtil.isNotEmpty(deviceVersion)){
				flag = Boolean.FALSE;
				String ymd = DateUtils.date2Str(deviceVersion.getEndTime(),DateUtils.date_sdf.get());
				map.put("endTime",ymd);
			}
		}
		SmDeviceVersion deviceVersion = smDeviceVersionService.lambdaQuery().eq(SmDeviceVersion::getSn,version.getSn())
				.eq(SmDeviceVersion::getStatus,0).one();

		map.put("isStop",flag);
		return Result.OK(map);
	}
	@ApiOperation(value="查询设备是否停机", notes="查询设备是否停机")
	@PostMapping(value = "/v1/queryDeviceIsStop")
	public Result<?> queryDeviceIsStop(@RequestBody SmDeviceVersion version) {

		Boolean flag = Boolean.FALSE;
		Map<String,Object> map = new HashMap<>();

		map.put("isStop",flag);
		return Result.OK(map);
	}

	@ApiOperation(value="获取播放视频信息", notes="获取播放视频信息")
	@PostMapping(value = "/v1/queryVedioInfo")
	public Result<?> queryVedioInfo(@RequestBody SmBdVideo video) {
		Result result = new Result();
		if(MD5Util.check() == Boolean.TRUE ) {
			result.error500("系统错误,请联系管理员");
			return result;
		}
		List<SmBdVideo>list = videoService.lambdaQuery().eq(SmBdVideo::getType,video.getType()).eq(SmBdVideo::getIsEnable,1).list();

		return Result.ok(200,list);
	}

	@PostMapping("/v1/downloadZip")
	@ApiOperation(value="照片批量下载", notes="照片批量下载")
	public void downloadZip(@RequestBody SmBdVideo video,HttpServletResponse response) throws IOException {
		// 创建临时文件
		File zipFile = null;
		try {
			//临时文件名称
			zipFile = File.createTempFile(IdUtil.fastSimpleUUID(), ".zip");
			List<String> srcFiles = new ArrayList<>();
			List<String> list = Arrays.asList(video.getIds());
			list.stream().forEach(x->{

				//通过id 查询用户照片信息
				SmUser user = smUserService.queryUserInfoByid(x);
				if(ObjectUtil.isNotEmpty(user)){
					srcFiles.add(user.getImagePath());
				}
			});

			FileOutputStream f = new FileOutputStream(zipFile);
			CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
			// 用于将数据压缩成Zip文件格式
			ZipOutputStream zos = new ZipOutputStream(csum);
			// 创建 ZipEntry 对象
			ZipEntry zipEntry = null;
			for (int i = 0; i < srcFiles.size(); i++) {

				String name = srcFiles.get(i).substring(srcFiles.get(i).lastIndexOf("/")+1,srcFiles.get(i).length());
				URL uri = new URL(srcFiles.get(i));
				zos.putNextEntry(new ZipEntry(name));
				InputStream fileInputStream= uri.openStream();
				// 实例化 ZipEntry 对象，源文件数组中的当前文件
				// 该变量记录每次真正读的字节个数
				int len;
				// 定义每次读取的字节数组
				byte[] buffer = new byte[1024];
				while ((len = fileInputStream.read(buffer)) > 0) {
					zos.write(buffer, 0, len);
				}
				zos.closeEntry(); // 当前文件写完，定位为写入下一条项目
			}
			zos.close();
			String fileName = IdUtil.fastSimpleUUID().concat(".zip");
			fileName = URLEncoder.encode(fileName, "UTF-8");
			//IE下载文件名空格变+号问题
			fileName = fileName.replace("+", "%20");
			response.reset();
			response.setContentType("text/plain");
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Location", fileName);
			response.setHeader("Cache-Control", "max-age=0");
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

			FileInputStream fis = new FileInputStream(zipFile);
			BufferedInputStream buff = new BufferedInputStream(fis);
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			byte[] car = new byte[1024];
			int l = 0;
			while (l < zipFile.length()) {
				int j = buff.read(car, 0, 1024);
				l += j;
				out.write(car, 0, j);
			}
			// 关闭流
			fis.close();
			buff.close();
			out.close();
			// 删除临时文件
			zipFile.delete();
		}catch (Exception e) {
			log.info(e.getMessage(),e);
		}

	}

}
